package com.example.mockapi.service

import com.example.mockapi.domain.ApiData
import com.example.mockapi.repository.ApiDataRepository
import org.apache.commons.logging.LogFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.stereotype.Service

@Service
class ApiDataService {

    @Autowired
    lateinit var apiDataRepository: ApiDataRepository

    val log = LogFactory.getLog(ApiDataService::class.java)!!

    fun save(api: String, entName: String, content: Any) {
        var apiData: ApiData?
        try {
            apiData = apiDataRepository.getByApiAndEntName(api, entName)
            apiData.content = content
        } catch (e: EmptyResultDataAccessException) {
            apiData = ApiData(null, api, entName, content)
        }
        if (apiData != null) {
            apiDataRepository.save(apiData)
        }
    }

    fun getByApi(api: String, entName: String) : Any {
        try {
            val apiData = apiDataRepository.getByApiAndEntName(api, entName)
            return apiData.content
        } catch (e: EmptyResultDataAccessException) {
            val errorContent = mapOf<String, Any>("status" to false, "errorCode" to 1104, "errorMessage" to "无法匹配到传入的企业全称")
            return errorContent
        }
    }
}